package nl.hu.modellingengine.ribbon.client.activity;

import java.util.ArrayList;

import nl.hu.modellingengine.client.ClientFactory;
import nl.hu.modellingengine.client.place.InitPlace;
import nl.hu.modellingengine.ribbon.client.RibbonFactory;
import nl.hu.modellingengine.ribbon.client.RibbonService;
import nl.hu.modellingengine.ribbon.client.RibbonServiceAsync;
import nl.hu.modellingengine.ribbon.client.view.RibbonColumn;
import nl.hu.modellingengine.ribbon.client.view.RibbonView;
import nl.hu.modellingengine.shared.ElementType;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;

public class RibbonInitActivity extends AbstractActivity implements RibbonView.Presenter{
	
	private ClientFactory clientFactory;
	private RibbonFactory ribbonFactory;
	private Boolean active = false;
	
	public RibbonInitActivity(InitPlace place, ClientFactory clientFactory,RibbonFactory ribbonFactory){
		this.clientFactory = clientFactory;
		this.ribbonFactory = ribbonFactory;
	}

	@Override
	public void start(AcceptsOneWidget containerWidget, EventBus eventBus) {
		RibbonView ribbonView = ribbonFactory.getRibbonView();
		ribbonView.setPresenter(this);
		
		RibbonServiceAsync ribbonService = (RibbonServiceAsync) GWT.create(RibbonService.class);
		
		ribbonService.getElementTypes("uml", "1", callbackElementTypes());
		active = true;
		
		containerWidget.setWidget(ribbonView);
	}

	@Override
	public void goTo(Place place) {
		clientFactory.getPlaceController().goTo(place);
	}
	
	private AsyncCallback<ArrayList<ElementType>> callbackElementTypes(){
		AsyncCallback<ArrayList<ElementType>> callback = new AsyncCallback<ArrayList<ElementType>>(){

			@Override
			public void onFailure(Throwable caught) {
				GWT.log(caught.getMessage());
				active= false;
			}

			@Override
			public void onSuccess(ArrayList<ElementType> result) {
				
				ArrayList<RibbonColumn> rcElements = new ArrayList<RibbonColumn>();
				for(ElementType elementType : result){
					rcElements.add(new RibbonColumn(elementType.getStrName(),elementType.getStrImageSource(),elementType.getDiagramType().getStrName()));		
				}
				RibbonView ribbonView = ribbonFactory.getRibbonView();
				ribbonView.setRibbons(rcElements);
				active = false;
			}
			
		};
		return callback;
	}
	
	
	

}
